const puppeteer = require("puppeteer-core")
const Window = require("./Window")

module.exports = class Browser {

    constructor(options = {}) {

        this.options = {
            headless: false,
            executablePath: "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
            ignoreDefaultArgs: ['--enable-automation'],
            defaultViewport: null,
            ...options
        }

        this.browser = null

        // 窗口列表
        this.windows = {}
    }

    // 打开浏览器
    async open() {

        // 创建浏览器
        this.browser = await puppeteer.launch(this.options)

        // 获取默认上下文
        const defaultContext = await this.browser.defaultBrowserContext()

        // 创建默认窗口对象
        this.windows.default = new Window(this, defaultContext, "default")
    }

    async close() {

        for (const name in this.windows) {
            if (name === "default") continue
            await this.windows[name].context.close()
        }
        this.windows = {}

        // 关闭浏览器
        await this.browser.close()

    }

    // 创建、获取窗口
    async window(name = "default", options = {}) {

        let window = this.windows[name]

        if (!window) {

            // 获取默认上下文
            const context = await this.browser.createBrowserContext(options)

            // 创建窗口对象
            window = new Window(this, context, name)

            // 缓存窗口对象
            this.windows[name] = window
        }

        return window

    }

    async closeWindow(name) {

        if (name === "default") return

        // 获取窗口对象
        const window = this.windows[name]

        // 关闭窗口
        await window.context.close()

        // 删除窗口对象
        delete this.windows[name]

    }



}